/**
  ETFRoot project, Anyang Normal University && IMP-CAS
  \class ETFTstart
  \brief a plastic scintillator placed at F1 of RIBLL2, single-ended
  \author SUN Yazhou, asia.rabbit@163.com
  \since 2021-10-30
  \date 2021-12-06 last modified
  \attention
  changelog
  <table>
  <tr>  <th>Date         <th>Author      <th>Description                   </tr>
  <tr>  <td>2021-10-30   <td>Asia Sun    <td>file created                  </tr>
  </table>

  \copyright Copyright (c) 2021 Anyang Normal U. && IMP-CAS with LGPLv3 LICENSE
*/

#include <cstring>
#include <TClonesArray.h>
#include "FairRootManager.h"
#include "ETFTstart.h"
#include "ETFDetectorManager.h"
#include "ETFPlaHit.h"
#include "ETFMath.h"
#include "ETFMsg.h"
#include "ETFHPTDCChannel.h"
#include "ETFParaManager.h"
#include "ETFYaml.h"

ClassImp(ETFTstart);

static const double DEGREE = ETFMath::DEGREE();
ETFTstart::ETFTstart(const char *name) : ETFTimer(name){
  const YAML::Node &chIdConfig = (*ETFParaManager::Instance()->GetChIdPara())[name];
  const int chId0 = chIdConfig.as<int>();
  if(chId0 >= 0){
    SetChIdMap(chId0, fDetId);
    SetChIdMap(chId0+1, fDetId + (1<<8));
  } // end if

  fHits = new TClonesArray("ETFPlaHit");
  fHits->SetName(name);
} // end ctor

// return the fired status of Tstop
int ETFTstart::GetFiredStatus() const{
  if(!fHits->GetEntries()) return -1;
  return dynamic_cast<ETFPlaHit *>((*fHits)[0])->GetFiredStatus();
} // end member function GetFiredStatus

// add the data channel to the detector
void ETFTstart::Assign(const ETFHPTDCChannel *ch){
  int uid = ETFDetectorManager::Instance()->GetUID(ch->GetChannelId());
  if(fDetId != (uid & 0xFF)) ETFMsg::Error("ETFTstart", "Assign: not from this detector.");
  bool vh = uid>>8 & 0x1;
  AddHit(ch, vh);
} // end member function Assign

void ETFTstart::AddHit(const ETFHPTDCChannel *ch, bool vh){
  ETFPlaHit *hit = nullptr;
  for(auto p : *fHits){
    ETFPlaHit *h = dynamic_cast<ETFPlaHit *>(p);
    if(h->GetStripId() == 0){ // old strip
      hit = h; continue;
    } // end if
  } // end for
  if(!hit){ // belongs to a new strip
    hit = dynamic_cast<ETFPlaHit *>(fHits->ConstructedAt(fHits->GetEntries()));
    hit->Initialize();
    hit->SetStripId(0);
    hit->SetLength(500.);
    hit->SetDelay(fDelay);
    // double pos[3]{}; hit->SetPosition(pos); // no need for position currently
    // TransformToLabRef(hit);
  } // end if
  hit->SetDataChannel(ch, vh);
} // end member function AddHit

// get the timing signal of Tstart
double ETFTstart::GetTime() const{
  if(!fHits->GetEntries()) ETFMsg::Error("ETFTstart", "GetTime: No hits in Tstart");
  return dynamic_cast<ETFPlaHit *>(fHits->At(0))->GetTimeU();
} // end member function GetTime
